package com.lyk.coursearrange.service.impl;

import com.lyk.coursearrange.dao.PaymentResultDao;
import com.lyk.coursearrange.entity.Installment;
import com.lyk.coursearrange.entity.PaymentResult;
import com.lyk.coursearrange.service.PaymentResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

@Service
public class PaymentResultServiceImpl implements PaymentResultService {
    @Autowired
    private PaymentResultDao paymentResultDao;

    @Override
    public PaymentResult processPayment(boolean diagnosticFeePaid, double totalAmount, int installmentNumber) {
        PaymentResult paymentResult = new PaymentResult();

        if (diagnosticFeePaid) {
            if (totalAmount == 1.0) {
                paymentResult.setMessage("全款支付，无需分期");
            } else {
                paymentResult.setMessage("全款支付，总金额：" + totalAmount);
            }

            // 计算并设置全款支付的时间
            calculatePaymentDate(paymentResult);
        } else {
            paymentResult.setMessage("分期支付，总金额：" + totalAmount);

            double installmentAmount = totalAmount / installmentNumber;
            paymentResult.setInstallmentNumber(installmentNumber);

            Installment[] installments = new Installment[installmentNumber];
            for (int i = 0; i < installmentNumber; i++) {
                installments[i] = new Installment(i+1, installmentAmount);
            }
            paymentResult.setInstallments(Arrays.asList(installments));
        }

        return paymentResult;
    }


    private void calculatePaymentDate(PaymentResult paymentResult) {
        // 简化示例，假设全款支付时间为当前日期
        LocalDate paymentDate = LocalDate.now();
        paymentResult.setPaymentDate(paymentDate);
    }
    /***
     * 对支付的增加
     * @param paymentResult
     */
    @Override
    public void addPaymentResult(PaymentResult paymentResult) {
        paymentResultDao.insert(paymentResult);
    }
    /***
     * 根据id查询全款分期付款记录
     * @param id
     * @return
     */
    @Override
    public PaymentResult getPaymentResultById(Long id) {
        return paymentResultDao.selectById(id);
    }
    /***
     * 查询所有全款分期付款
     * @return
     */
    @Override
    public List<PaymentResult> getAllPaymentResults() {
        return paymentResultDao.selectList(null);
    }
    /***
     * 更新全款分期付款记录
     * @param paymentResult
     * @return
     */
    @Override
    public void updatePaymentResult(PaymentResult paymentResult) {
        paymentResultDao.updateById(paymentResult);
    }
    /***
     * 根据id删除全款分期记录
     * @param id
     * @return
     */
    @Override
    public void deletePaymentResultById(Long id) {
        paymentResultDao.deleteById(id);

    }

}
